#pragma once

#include <queue>
#include <mutex>
#include <thread>
#include <condition_variable>

template <class T>
class LockQueue
{
public:
    LockQueue() {}
    ~LockQueue() {}
    void Push(const T &data)
    {
        // 多个线程都会往日志队列写日志
        std::unique_lock<std::mutex> lock(m_mutex);
        m_queue.push(data);
        // 唤醒日志线程
        m_cond.notify_one();
    }
    T Pop()
    {
        // 一个IO线程负责从日志队列拿数据写入文件
        std::unique_lock<std::mutex> lock(m_mutex);
        // 采用while循环判断，防止线程假唤醒
        while (m_queue.empty())
        {
            // 如果队列为空，则阻塞等待被唤醒
            m_cond.wait(lock);
        }
        T data = m_queue.front();
        m_queue.pop();
        return data;
    }

private:
    std::queue<T> m_queue;
    std::mutex m_mutex;
    std::condition_variable m_cond;
};
